package org.example.stockdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.stockdemo.entity.StockDetail;
import org.example.stockdemo.mapper.StockDetailMapper;
import org.example.stockdemo.service.StockDetailService;
import org.example.stockdemo.service.TencentStockService;
import org.example.stockdemo.util.BeanExtUtil;
import org.example.stockdemo.vo.FundTrendItemListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class StockDetailServiceImpl extends ServiceImpl<StockDetailMapper, StockDetail> implements StockDetailService {

    @Autowired
    private StockDetailMapper stockDetailMapper;
    @Autowired
    private TencentStockService tencentStockService;


    @Transactional
    @Override
    public boolean batchSaveStock(List<StockDetail> stockDetails) {
        if (CollectionUtils.isNotEmpty(stockDetails)) {
            LocalDate now = LocalDate.now();
            LocalDateTime dateTime = LocalDateTime.now();

            List<String> codes = stockDetails.stream().map(StockDetail::getCode).collect(Collectors.toList());
            LambdaQueryWrapper<StockDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(StockDetail::getCode, codes);
            queryWrapper.eq(StockDetail::getCreatedAt, now);

            // 根据code,日期查询
            List<String> existingCodeResult = list(queryWrapper).stream().map(StockDetail::getCode).collect(Collectors.toList());

            List<StockDetail> stockCpList = BeanExtUtil.copyList(stockDetails, StockDetail.class);

            List<StockDetail> upDetailList = new ArrayList<>();
            Iterator<StockDetail> iterator = stockCpList.iterator();
            while (iterator.hasNext()) {
                StockDetail stockDetail = iterator.next();
                stockDetail.setCreatedAt(now);
                stockDetail.setUpdatedAt(dateTime);
                if (existingCodeResult.contains(stockDetail.getCode())) {
                    upDetailList.add(stockDetail);
                    iterator.remove();
                }
            }

            // 批量更新
            if (CollectionUtils.isNotEmpty(upDetailList)) {
                for (StockDetail stockDetail : upDetailList) {
                    UpdateWrapper updateWrapper = new UpdateWrapper();
                    updateWrapper.eq("code", stockDetail.getCode());
                    updateWrapper.eq("created_at", now);
                    stockDetailMapper.update(stockDetail, updateWrapper);
                }
            }
            //批量插入
            if (CollectionUtils.isNotEmpty(stockCpList)) {
                return saveBatch(stockCpList);
            }
        }
        return false;
    }

    @Transactional
    @Override
    public StockDetail getStockDetailByCode(String code) {
        LambdaQueryWrapper<StockDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StockDetail::getCode, code);
        queryWrapper.eq(StockDetail::getCreatedAt, LocalDate.now());
        StockDetail stockDetail = stockDetailMapper.selectOne(queryWrapper);
        if (stockDetail == null){
            stockDetail = tencentStockService.getRealtimeQuote(code);
        }else {
            if (Objects.isNull(stockDetail.getYesterdayPrice()) || stockDetail.getYesterdayPrice() == 0) {
                StockDetail realtimeQuote = tencentStockService.getRealtimeQuote(code);
                stockDetail.setStartPrice(realtimeQuote.getStartPrice());
                stockDetail.setYesterdayPrice(realtimeQuote.getYesterdayPrice());
                stockDetail.setHighPrice(realtimeQuote.getChangeValue());
                stockDetail.setLowPrice(realtimeQuote.getChangePercent());
                stockDetailMapper.updateById(stockDetail);
            }
        }
        stockDetail.setCode(code);
        return stockDetail;
    }

    @Override
    public FundTrendItemListVO getMinuteData(String stockCode) {
        FundTrendItemListVO minuteData = tencentStockService.getMinuteData(stockCode);
        StockDetail stockDetail = getStockDetailByCode(stockCode);
        Double startPrice = stockDetail.getStartPrice();
        Double yesterdayPrice = stockDetail.getYesterdayPrice();
        // 计算开盘涨幅
        double startPencent = (startPrice - yesterdayPrice) / yesterdayPrice * 100;
        // 计算1分钟涨幅百分比
        calculatePriceChanges(minuteData,yesterdayPrice,startPencent);
        return minuteData;
    }


    /**
     * 遍历价格列表，计算涨幅，并放入minuteData
     * @param minuteData 分时数据
     * @return 包含涨幅数据的分时数据
     */
    public FundTrendItemListVO calculatePriceChanges(FundTrendItemListVO minuteData,double yesterdayPrice,double startPencent) {
        if (minuteData == null || minuteData.getPriceList() == null || minuteData.getPriceList().isEmpty()) {
            return minuteData;
        }


        List<Double> priceList = minuteData.getPriceList();
        List<Double> changeList = new ArrayList<>();
        
        // 第一个价格为开盘涨幅
        changeList.add(startPencent);
        
        // 计算每个价格相对于前一个价格的涨幅
        for (int i = 1; i < priceList.size(); i++) {
            Double currentPrice = priceList.get(i);
            double change = ((currentPrice - yesterdayPrice) / yesterdayPrice) * 100;
            changeList.add(change);
        }
        
        // 将涨幅数据存储到changeList字段中
        minuteData.setChangePercentList(changeList);
        
        return minuteData;
    }


}